package com.tongsys.server.controller;

import com.tongsys.server.config.redis.RedisUtils;
import com.tongsys.server.entity.User;
import com.tongsys.server.utils.JwtUtils;
import com.tongsys.server.utils.RtnUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpClient;
import java.util.concurrent.TimeUnit;

@ApiOperation("刷新token ")
@RestController
@RequestMapping("/api/token")
public class RefreshTokenController {

    @Autowired
    private RedisUtils redisUtils;
    @PostMapping("/refresh")
    public RtnUtils refreshToken(HttpServletRequest request){
        //获取请求中的token
        String token=null;
        //获取请求头中的token
        token=request.getHeader("token");

        //获取请求参数中的token
        if (StringUtils.isEmpty(token)){
            token=request.getParameter("token");
        }

        //获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取用户信息
        User user = (User) authentication.getPrincipal();

        String newToken=null;
        //验证token,生成新token
        if (JwtUtils.checkToken(token,user)){
            newToken = JwtUtils.createToken(user.getId());
        }
        long expire = 0;
        //获取本次token的过期时间
        if (newToken!=null){
            expire=JwtUtils.getExpire(newToken);
        }

        //清除redis中的token
        String key="login:"+token;
        redisUtils.deleteObject(key);

        //在redis中保存新的token
        redisUtils.setCacheObject("login:"+user.getId(),newToken);
        return RtnUtils.ok().data(newToken).msg("刷新token成功");
    }


}
